package kit.docker.redis;

import com.jfinal.config.Plugins;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.RedisPlugin;

import java.util.LinkedHashMap;
import java.util.Map;

public abstract class RedisConnectKit {

    private static final Map<String, RedisBean> redisMap = new LinkedHashMap<String, RedisBean>();

    public static Map<String, RedisBean> getRedisMap() {
        if (redisMap.isEmpty()) {
            parseRedisInfo();
        }
        return redisMap;
    }

    public static RedisBean getRedis(String name) {
        if (redisMap.isEmpty()) {
            parseRedisInfo();
        }
        return redisMap.get(name);
    }

    private static void parseRedisInfo() {
        String redis_start = "redis[";
        String redis_end = "]";
        String prefix = null;

        String name = null;
        String password = null;
        String host = null;
        int port = 6379;

        int initialSize = 0;
        int minIdle = 0;
        int maxActive = 8;
        int timeout = 0;

        RedisBean redis = null;

        int count = PropKit.getInt(RedisConstant.redis_count);
        for (int i = 1; i <= count; i++) {
            prefix = redis_start + i + redis_end + ".";

            name = PropKit.get(prefix + RedisConstant.redis_name);
            host = PropKit.get(prefix + RedisConstant.redis_host);
            port = PropKit.getInt(prefix + RedisConstant.redis_port);
            password = PropKit.get(prefix + RedisConstant.redis_password);
            initialSize = PropKit.getInt(prefix + RedisConstant.redis_initial_size, initialSize);
            minIdle = PropKit.getInt(prefix + RedisConstant.redis_min_idle, minIdle);
            maxActive = PropKit.getInt(prefix + RedisConstant.redis_max_active, maxActive);
            timeout = PropKit.getInt(prefix + RedisConstant.redis_timeout, timeout);

            redis = new RedisBean();

            redis.setName(name);
            redis.setHost(host);
            redis.setPort(port);
            redis.setPassword(password);
            redis.setInitialSize(initialSize);
            redis.setMinIdle(minIdle);
            redis.setMaxActive(maxActive);
            redis.setTimeout(timeout);

            redisMap.put(name, redis);
        }
    }

    public static void connect(Plugins plugins) {
        Map<String, RedisBean> redisMap = getRedisMap();
        for (String name : redisMap.keySet()) {
            RedisBean redis = redisMap.get(name);
            if (StrKit.isBlank(redis.getPassword())) {
                RedisPlugin redisPlugin = new RedisPlugin(redis.getName(), redis.getHost(), redis.getPort());
                plugins.add(redisPlugin);
            } else {
                RedisPlugin redisPlugin = new RedisPlugin(redis.getName(), redis.getHost(), redis.getPort(), redis.getPassword());
                plugins.add(redisPlugin);
            }
        }
    }
}
